
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,

        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}

let operationList=[];
let salesmanList=[];
let deptOperationList=[];
let deptSalesmanList=[];
//select over
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        operationList=getxmselect("#operationCode","operationCode", userTree);
        salesmanList=getxmselect("#salesmanCode","salesmanCode", userTree);
    }else {
        operationList=getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}]);
        salesmanList=getxmselect("#salesmanCode","salesmanCode", [{name: user.name, value: user.code}]);
    }
    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }

})()
layui.use(['dropdown'], function () {
    var dropdown = layui.dropdown;
    dropdown.onFilter("printfn", function (event) {
        var checkStatus = table.checkStatus("tasktableid");

        switch (event) {
            case "warehousePurchase":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个备货合同! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的备货合同! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=warehousePurchaseReport&code=code:"+checkStatus.data[0].id)
                break

        }
    });
})

let isMsn="否";
layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("contractStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/ExportBusiness/tpl/taskStatistics1.jsp","任务(备货合同)产品交期一览表")
                break
            case "s2":
                parent.intab("views/jsp/ExportBusiness/tpl/taskPurchaseStatistics.jsp","备货采购情况")
                break
        }
    });
})

lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});


layer.ready(function () {
    $.ajax({
        url: 'billChange/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn=date.data
        }
    })

    //获取所有公司信息
    $.ajax({
        url:"receivePayment/getCompanyInfo",
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    //公司名称
                    $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });

    let searchURL = window.location.search;
    searchURL = searchURL.substring(1, searchURL.length);
    let type = searchURL.split("&")[0].split("=")[1];
    let obj = {operationCode : user.code, salesmanCode : user.code};
    if(!isEmpty(type) && type == "statistics"){
        //来源于控制台统计

        //获取当月开始日期
        let time = new Date();
        let month = ("0" + (time.getMonth() + 1)).slice(-2);
        let year = time.getFullYear();
        //获取当月第一天
        let startDay = new Date(year, month, 1);
        let startCurryDay = startDay.getDate();
        startCurryDay = startCurryDay < 10 ? '0' + startCurryDay : startCurryDay;
        let startDate = time.getFullYear() + "-" + (month) + "-" + (startCurryDay);
        //签约日期
        laydate.render({
            elem: '#signingDateStart',
            value: startDate,
            isInitValue: true
        });

        //获取当月结束日期
        let endDay = new Date(year, month, 0);
        let endCurryDay = endDay.getDate();
        endCurryDay = endCurryDay < 10 ? '0' + endCurryDay : endCurryDay;
        let endDate = time.getFullYear() + "-" + (month) + "-" + (endCurryDay);
        //签约日期
        laydate.render({
            elem: '#signingDateEnd',
            value: endDate,
            isInitValue: true
        });

        obj = {operationCode : user.code, signingDateStart : startDate, signingDateEnd : endDate, statusList : "1,2,3,4"}
    }

    initTable(obj);
});

document.getElementById('clear').onclick = function(){
    operationList.setValue([ ]);
    salesmanList.setValue([ ]);
    deptSalesmanList.setValue([ ]);
    deptOperationList.setValue([ ]);
};

form.render();//表单刷新
function initTable(obj){
    table.render({
        elem: '#taskselect'
        ,where:obj
        ,url:'task/getListByPage'
        ,toolbar: '#tasktoolbar'
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field:'billNo', title:'合同编号',sort:true,width: 220,event: "contractno"}
            ,{field:'customerName', title:'客户名称',sort:true,width: 120}
            ,{field:'customerContactNo', title:'客户合同号',sort:true,width: 120}
            ,{field:'signingDate', title:'签约日期',sort:true,width: 120}
            ,{field:'signingCompanyName', title:'签约公司',sort:true,width: 220}
            ,{field:'transitPlaceName', title:'起运地',sort:true,width: 120}
            ,{field:'destinationName', title:'目的地',sort:true,width: 120}
            ,{field:'currency', title:'币种',sort:true,width: 120}
            ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120}
            ,{field:'usdRate', title:'美元汇率',sort:true,width: 120}
            ,{field:'leadTime', title:'备货期限',sort:true,width: 120}
            ,{field:'carryTime', title:'出运日期',sort:true,width: 120}
            ,{field:'priceTermsName', title:'价格术语',sort:true,width: 120}
            ,{field:'paymentTerm', title:'付款期限',sort:true,width: 120}
            ,{field:'salesmanName', title:'业务员',sort:true,width: 120}
            ,{field:'businessModelName', title:'业务模式',sort:true,width: 120}
            ,{field:'rechargeOccupancy', title:'充值占用',sort:true,width: 120,templet: function(data){
                    if(0 == data.rechargeOccupancy){
                        return "否";
                    }else {
                        return "是";
                    }
                }}
            ,{field:'customerAccountingPeriod', title:'客户账期',sort:true,width: 120}
            ,{field:'customerComplaintNo', title:'客诉单号',sort:true,width: 120}
            ,{field:'operator', title:'操作员',sort:true,width: 120}
            ,{field:'advancePaymentRatio', title:'预收款比例',sort:true,width: 120}
            ,{field:'advancePaymentAmount', title:'预收款金额',sort:true,width: 120}
            ,{field:'totalContractAmount', title:'合同总额',sort:true,width: 120}
            ,{field:'memo', title:'备注', width: 220}
            /*,{fixed: 'right', width:240, toolbar: '#taskeditor', title:'操作'}*/
            ,{fixed: 'right', width:240, title:'操作',templet: function(d){
                    // 单据状态/类型（1：草稿箱，2：待批箱，3：已批箱，4：完成箱，5垃圾箱）
                    if(isMsn=="是"){//管理员
                        var html="<div>"
                        if(d.status==1 || d.status==2|| d.status==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                        }
                        if(d.status==1){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                        }
                        if(d.status==2){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"through\">审批通过</a>"
                        }
                        if(d.status==2 || d.status==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                        }
                        if(d.status==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                        }
                        if(d.status==5){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">彻底删除</a>"
                        }
                        return html+"</div>";
                    }else {
                        var html = "<div>"
                        if (d.status == 1) {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                        }
                        if (d.status == 2) {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                        }
                        if(d.status==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                        }
                        if(d.status==5){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">彻底删除</a>"
                        }
                        return html + "</div>";
                    }
                }}
        ]]
        ,id: 'tasktableid'
        ,height: $(document).height() - $('#taskselect').offset().top - 50
        ,page: true
        ,limit: 50
        ,limits: [50, 100, 200, 300, 500]
    });
}
table.on('tool(tasktable)', function(obj){
    let data = obj.data;
    let id = data.id;
    if(obj.event === 'update') {
        //1:采购调用  0:未被调用
        let res = getUsedDataInfo(id, data.billNo);
        if(res === 0){
            parent.intab("views/jsp/ExportBusiness/tpl/updateTask.jsp?id="+obj.data.id,"修改备货合同（任务）")
        }else if(res === 1){
            layer.msg("已做采购，无法修改", {icon: 5});
        }
    }else if(obj.event === 'delect'){
        layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
            layer.close(index);
            let dataBases={
                id:id,
                status:data.status
            }
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(dataBases),
                url:"task/delete",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("删除成功", {icon: 6});
                        table.reload('tasktableid', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                            ,where: data.field
                        }, 'data');
                        return false;
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            });
        });
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', confirmInfo(3, 5), function (index) {
            operationData(data, 1, "提交审批");
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', confirmInfo(3, 5), function (index) {
            operationData(data, 2, "审批通过");
        });
    }else if(obj.event === 'backtothe'){
        //1:采购调用  0:未被调用
        let res = getUsedDataInfo(id, data.billNo);
        if(res === 0){
            layer.confirm('确定审批退回吗', confirmInfo(3, 5), function (index) {
                operationData(data, 3, "审批退回");
            });
        }else if(res === 1){
            layer.msg("已做采购，无法退回", {icon: 5});
        }
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', confirmInfo(3, 5), function (index) {
            operationData(data, 4, "完成");
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', confirmInfo(3, 5), function (index) {
            operationData(data, 5, "还原");
        });
    }else if (obj.event === "contractno"){
        parent.intab("views/jsp/ExportBusiness/tpl/viewtask.jsp?id="+obj.data.id,"备货合同（任务）明细")
    }
});

//1:采购调用  0:未被调用
function getUsedDataInfo(id, billNo) {
    let countNum = 0;
    $.ajax({
        url: "task/checkIsCanModified?id=" + id + "&billNo=" + billNo,
        async: false,
        success: function (res) {
            if (res.status == 200) {
                countNum = res.data;
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    return countNum;
}

function operationData(data, operation, msg){
    let fields = {
        id : data.id,
        billNo : data.billNo,
        operation: operation
    }
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(fields),
        url:"task/operation",
        success:function(res){
            if(res.status == 200){
                layer.msg(msg, {icon: 6});
                table.reload('tasktableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: data.field
                }, 'data');
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

form.on('submit(submitform)', function(data){
    initTable(data.field);
    return false;
});

table.on('toolbar(tasktable)', function(obj){
    let checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/ExportBusiness/tpl/newuptask.jsp","新增备货合同（任务）");
            break;
        case 'copys':
            var data = checkStatus.data;
            if(data.length == 1){
                parent.intab("views/jsp/ExportBusiness/tpl/copyTask.jsp?id="+data[0].id,"复制备货合同（任务）");
            }else{
                layer.msg("复制合同请选取一个数据进行操作")
            }
            break;
    };
});

// $("#statistical").on("click",function () {
//     parent.intab("views/jsp/ExportBusiness/tpl/statistics.jsp","备货合同（任务）统计")
// });

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}